<template>
  <el-upload
    ref="uploadRef"
    class="upload-demo"
    :action="action"
    :auto-upload="false"
    :show-file-list="true"
    :limit="limit"
    :accept="accept"
    name="iFile"
    drag
    @success="handleSuccess"
  >
    <el-icon><Plus /></el-icon>
    <div class="el-upload__text">单击或拖拽文件到此处</div>
    <template #tip>
      <div class="el-upload__tip">
        {{ tipText }}
        <el-button type="primary" size="small" class="upload-button" @click="submitUpload">确认上传</el-button>
      </div>
    </template>
  </el-upload>
  <div v-if="filePaths.length > 0">
    <p v-for="(path, index) in filePaths" :key="index">文件上传成功，路径为：{{ path }}</p>
  </div>
</template>

<script>
import { ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  props: {
    action: {
      type: String,
      required: true
    },
    limit: {
      type: Number,
      required: true
    },
    accept: {
      type: String,
      required: true
    },
    tipText: {
      type: String,
      required: true
    }
  },
  emits: ['ocrData'],
  setup(props, { emit }) {
    const uploadRef = ref(null);
    const filePaths = ref([]);

    const submitUpload = () => {
      if (uploadRef.value) {
        uploadRef.value.submit();
      }
    };

    const handleSuccess = async (response, file, fileList) => {
      if (response.code === 200) {
        filePaths.value.push(response.data.file_path);
        ElMessage({
          message: `上传成功: ${response.msg}`,
          type: 'success',
        });

        console.log('文件上传成功，路径为:', response.data.file_path);
        console.log('当前文件路径列表:', filePaths.value);

        // 检查是否有两个文件路径
        if (filePaths.value.length === 2) {
          const imageD = encodeURIComponent(filePaths.value[0]);
          const imageS = encodeURIComponent(filePaths.value[1]);

          console.log('准备调用 OCR 接口，参数为:', {
            app_id: 10001,
            imageD: imageD,
            imageS: imageS
          });

          // 调用 OCR 接口
          try {
            const ocrResponse = await axios.get(`http://111.229.78.177:8000/api/customs.Declaration/OCR?app_id=10001&imageD=${imageD}&imageS=${imageS}`);
            if (ocrResponse.data.code === 200) {
              ElMessage({
                message: 'OCR 处理成功',
                type: 'success',
              });
              console.log('OCR 处理成功，响应数据为:', ocrResponse.data);

              // 传递 OCR 数据给父组件
              emit('ocrData', ocrResponse.data.map, ocrResponse.data.table);
            } else {
              ElMessage({
                message: `OCR 处理失败: ${ocrResponse.data.message}`,
                type: 'error',
              });
              console.log('OCR 处理失败，错误信息为:', ocrResponse.data.message);
            }
          } catch (error) {
            ElMessage({
              message: `OCR 请求失败: ${error.message}`,
              type: 'error',
            });
            console.log('OCR 请求失败，错误信息为:', error.message);
          }
        }
      } else {
        ElMessage({
          message: `上传失败: ${response.msg}`,
          type: 'error',
        });
        console.log('上传失败，错误信息为:', response.msg);
      }
    };

    return {
      uploadRef,
      submitUpload,
      handleSuccess,
      filePaths
    };
  }
};
</script>

<style scoped>
.upload-button {
  float: right;
}
</style>